<template>
	<view>
		<!-- <u-navbar :title="title"></u-navbar> -->
		<view v-if="submitFlag" style="position: fixed;z-index: 9999;left:0;top:0;right:0;bottom:0; background: #fff;display: flex;flex-direction: column;justify-content: center;align-items: center;">
			<result v-if="showResult" :isExercise="isExercise" :resultInfo="resultInfo" @showAnswer="onShowAnswer" @tryAgain="onTryAgain"/>
			<template v-else>
				<image src="./u3060.gif" style="width: 200rpx;height:200rpx"></image>
				<view style="color: #FF8282;">正在进行评分请稍后</view>
			</template>
		</view>
		<view class="wrap">
			<view class="item" style="width: 30%;background-color: #fff; padding-left: 20rpx;">
				<text>
					合格率：{{examInfo.correctRate || 0}}%
				</text>
			</view>
			<view class="item" style="width: 45%;background-color: #fff; padding-left: 20rpx;">
				<text>
					剩余时间：<u-count-down ref="refCountDown" 
										:timestamp="(examInfo.examDuration || 30) *60" 
										:autoplay="false"
										@change="onCountDownChange"
										color="#EA655E" separator-color="#EA655E"></u-count-down>
				</text>
			</view>
			<view class="item" style="width: 25%;background-color: #fff;text-align: center;">
				<text style="" @tap="showCardModal" data-target="modalCard">
					<u-icon name="order" color="#999999" size="36"></u-icon>
					<text>
						{{questionIndex+1}}/{{totalNumber}}
					</text>
				</text>
			</view>
		</view>
		<u-gap bg-color="#f5f5f5" :height="20"></u-gap>
		<!-- 题目 -->
		<view class="uni-padding-wrap uni-common-mt">
			<swiper :current="questionIndex" class="swiper-box" @change="swiperChange" :style="{'height':swiperHeight,'background':'#ffffff'}">
				<swiper-item v-for="(question,index) in questionList" :key="index">
					<!-- 题目 -->
					<view class="cu-bar bg-white solid-bottom">
						<view class="action">
							<u-tag :text="question.questionType == 1?'单选题':'多选题'" shape="circle" border-color="#ffffff" bg-color="#EA655E" color="#ffffff" type="success" />
							<text class="cuIcon-title text-red"></text>第{{index + 1}}题 ({{question.questionScore}}分)
						</view>
						<view class="txt-title">
							{{question.questionContent}}
						</view>
					</view>
					<view>
						<!--单选-->
						<radio-group class="block" @change="radioboxChange" v-if="question.questionType===1">
							<view class="cu-form-group" v-for="(option,index) in question.optionList" :key="index" style="width:100%;">
								<view class="title">	<radio :value="option.optionCode" :disabled="activeDisabled">{{option.optionCode}}. {{option.optionContent}}</radio></view>
							</view>
						</radio-group>
						<!--多选-->
						<checkbox-group class="block" @change="checkboxChange" v-else-if="question.questionType===2">
							<label class="cu-form-group" v-for="(option,index) in question.optionList" :key="index" style="">
								<checkbox :disabled="activeDisabled" :value="option.optionCode" :class="option.isSelect?'checked':''"
								 >
								</checkbox>
								<view class="title">
									<text>{{option.optionCode}}. {{option.optionContent}}</text>
								</view>
							</label>
						</checkbox-group>
					</view>
					<view v-show="showAnswer" class="margin-top solid-top" style="margin-top:30rpx;border-top:1px solid #f5f5f5;">
						<view class="cu-bar u-m-t-20 u-m-b-20">
							<view class="action text-grey">
								<text>正确答案：</text>
								<text class="solid-bottom  padding-left text-green">{{question.answer}}</text>
							</view>
						</view>
						<!-- <view class="cu-bar cu-bar-title">
							<view class="action  text-grey">
								<text>解析：</text>
							</view>
						</view>
						<view class="text-content padding  text-grey">
							{{question.explain}}
						</view> -->
					</view>
				</swiper-item>
			</swiper>
			<view  style="text-align: center; padding: 25rpx;width:100%; position: fixed; bottom: 0; background:#fff;">
				<u-button  @click="moveQuestion(-1)" shape="circle" class="u-m-r-15" size="medium" :disabled="questionIndex == 0">上一题</u-button>
				<u-button v-if="questionIndex < questionList.length-1 || showAnswer" @click="moveQuestion(1)" shape="circle" class="u-m-l-15" size="medium" :disabled="questionIndex == questionList.length-1">下一题</u-button>
				<u-button v-else @click="modalCard = true" shape="circle" class="u-m-l-15" size="medium">交卷</u-button>
			</view>
		</view>
		<u-popup v-model="modalCard" mode="top" :mask="true">
			<view class="cu-dialog" @tap.stop>
				<view class="page padding">
					<view v-for="(item,idx) in questionList" :key="idx" :class="[item.userAnswer && item.userAnswer.length>0 ? 'red-border-a':'red-border-b']"
					 style="display: inline-block;width: 90rpx;height: 90rpx;margin-right: 30rpx; margin-bottom:20rpx; border:1px solid #dedede; text-align: center;line-height: 90rpx;border-radius: 100%;"
					 :style="questionIndex == idx? 'background:red;color:#fff;':''"
					 @click="appointedQuestion(idx)"
					 >  {{idx+1}}</view>
				</view>
				<view style="text-align: center;padding-bottom: 40upx;">
					<button shape="circle" :custom-style="customStyle" size="medium " @click="show()">交卷</button>
				</view>
			</view>
		</u-popup>

		<unik-modal ref="unikModal"  :modalTitle="modalTitle"  @confirmModal="confirmModal" @cancelModal="cancelModal">
			<view style='font-size: 14px;padding: 15px;'>
				还有 <text style="color: #f00;">{{ noAnswerNumber }}</text> 题未做,
				是否确认提交?
			</view>
		</unik-modal>
		
		<u-toast ref="uToast" />

	</view>
</template>

<script>
	import unikModal from '../../components/modal/Modal.vue';
	import result from './result.vue';
	export default {
		components:{
			unikModal,
			result
		},
		data() {
			return {
				title:'',
				customStyle: {
					marginTop: '20px', // 注意驼峰命名，并且值必须用引号包括，因为这是对象
					color: 'red'
				},
				mask:false,
				day : `${new Date().getFullYear()}-${new Date().getMonth()+1>=10? new Date().getMonth()+1 :'0'+(new Date().getMonth()+1)}-${new Date().getDate()>=10 ?new Date().getDate():'0'+new Date().getDate()}`,
				popupShow:false,
				cardList:[],
				answerArr: [], //定义一个数组 装答案
				userAnswerArr: [], //选择的答案的数组
				activeShow: true,
				confrimShow: false,
				showNameAndTel: false,
				hiddeBtnAndTime: true, //隐藏时间和提交按钮
				activeDisabled: false, //单选、多选按钮不可编辑
				showAnswerBtn: true, //显示答案解析
				totalNumber: 0,
				modalTitle: '', //确认按钮标题
				noAnswerNumber: 0, // 未答题数
				questionIndex: 0, //跳转索引
				autoRadioNext: true, //单选题，自动移下一题
				swiperHeight: '650px', //
				modalCard: null, //显示答题卡
				questionList: [],
				startTime:0,
				endTime:0,
				classifyId:'',
				examInfo:{},
				submitFlag: false,
				showResult: false, 
				resultInfo: {},
				showAnswer: false,
				isExercise: false // 是否是练习
			}
		},
		onReady() {
			var tempHeight = 800;
			var _me = this;
			uni.getSystemInfo({
				//获取手机屏幕高度信息，让swiper的高度和手机屏幕一样高                
				success: function(res) {
					tempHeight = res.windowHeight;
					uni.createSelectorQuery().select("#top-box").fields({
						size: true,
						scrollOffset: true
					}, (data) => {
						tempHeight -= data.height;
						uni.createSelectorQuery().select("#foot-box").fields({
							size: true,
							scrollOffset: true
						}, (data) => {
							tempHeight -= data.height;
							_me.swiperHeight = tempHeight + 'px';
						}).exec();
		
					}).exec();
				}
			});
		
		},
		onLoad(option) {
			// this.submitFlag = true
			// this.showResult = true
			// this.resultInfo = uni.getStorageSync('examInfo')
			// return
			let {examId,examName, isExercise} = option
			this.classifyId = examId
			this.title = examName
			this.isExercise = isExercise == 1

			this.startTime = this.day + ` ${new Date().getHours()>=10?new Date().getHours():'0'+new Date().getHours()}:${new Date().getMinutes()>=10?new Date().getMinutes():'0'+new Date().getMinutes()}:${new Date().getSeconds()>=10?new Date().getSeconds():'0'+new Date().getSeconds()}`
			this.getQuestionList(examId)
		},
		methods:{
			getQuestionList(id){
				this.$http.getQuestionList(id).then(res => {
						if(!res.data || !res.data.questionList || !res.data.questionList.length){
							return
						}
						this.$refs.refCountDown.start()
						this.examInfo = res.data;
						res.data.questionList.forEach((question, index) => {
							question.id = index+1
							question.answer = question.optionList.filter(item => item.isRight == 1).map(item => item.optionCode).join(',')
							question.userAnswer = []
							question.optionList.forEach(opt => opt.isSelect = 0)
						})

						this.questionList = res.data.questionList
						this.totalNumber = this.questionList.length
				})
			},
			// 提交按钮
			show: function() {
				let noAnswerList = this.questionList.filter(item => !item.userAnswer || !item.userAnswer.length)
				this.noAnswerNumber = noAnswerList.length
				this.modalCard = !this.modalCard
				this.mask = !this.mask
				if(this.noAnswerNumber){
					this.$refs.unikModal.show()
					return
				} 
				this.confirmModal()
			},
			onCountDownChange(timestamp){
				if(timestamp == 0){
					this.$refs.uToast.show({title: '时间到!'})
					this.confirmModal()
				}

			},
			//确认提交
			confirmModal:function() {
				let questionList = this.questionList.map(question => {
					question.optionList.forEach(opt => 
						opt.isSelect = question.userAnswer.includes(opt.optionCode) ? 1 : 0
					)
					question.questionAnswer = question.userAnswer.join(',')
					return question
				})
				this.endTime = this.day + ` ${new Date().getHours()>=10?new Date().getHours():'0'+new Date().getHours()}:${new Date().getMinutes()>=10?new Date().getMinutes():'0'+new Date().getMinutes()}:${new Date().getSeconds()>=10?new Date().getSeconds():'0'+new Date().getSeconds()}`;
				this.$refs.refCountDown.end()
				const submitData = Object.assign({},this.examInfo,{questionList})
				submitData.startTime= this.startTime
				submitData.endTime= this.endTime
				submitData.isExercise = this.isExercise ? 1 : 0
				this.submitFlag = true
				this.$http.calculateScore(submitData).then(res => {
					this.showResult = true
					res.data.questionList.forEach((item, index) => item.id = index+1)
					res.data.examName = this.examInfo.examName
					this.resultInfo = res.data
					uni.setStorageSync('examInfo', res.data)
				}).catch(() => {
					this.submitFlag = false
				})
			},
			//取消
			cancelModal() {
				this.mask = !this.mask;
			},
			//题卡指定
			appointedQuestion: function(e) {
				this.modalCard = null;
				this.questionIndex = e;
			},
			//显示题卡
			showCardModal: function(e) {
				if(this.showAnswer) return
				this.modalCard = e.currentTarget.dataset.target
			},
			//隐藏题卡
			hideCardModal: function(e) {
				this.modalCard = null
			},
			//滑动事件
			swiperChange: function(e) {
				let index = e.target.current;
				if (index != undefined) {
					this.questionIndex = index;
				}
			},
			//单选选中
			radioboxChange: function(e) {
				var values = e.detail.value; //e.detail.value 用户的选择
				let curQuestion = this.questionList[this.questionIndex]
				curQuestion.userAnswer = [values];
			},
			//复选选中
			checkboxChange: function(e) {
				var values = e.detail.value;
				let curQuestion = this.questionList[this.questionIndex]
				curQuestion.userAnswer = values
			},
			//上一题、下一题
			moveQuestion: function(e) {
				if (e === -1 && this.questionIndex != 0) {
					this.questionIndex -= 1;
				}
				if (e === 1 && this.questionIndex < this.questionList.length - 1) {
					this.questionIndex += 1;
				}
			},

			onShowAnswer(){
				this.questionIndex = 0
				this.submitFlag = false
				this.showResult = false
				this.showAnswer = true
			},
			onTryAgain(){
				this.questionIndex = 0
				this.submitFlag = false
				this.showResult = false
				this.showAnswer = false
				this.getQuestionList(this.classifyId)
			}
		}
	}
</script>

<style lang="scss" scoped>
	// /deep/ .u-drawer{
	// 	top:160upx;
	// }
	// /deep/ .u-mask-show{
	// 	top:160upx;
	// }
	.wrap{
		display: flex;
		flex-direction: row;
		align-items: center;
		background-color: #FFFFFF;
	}
	.wrap .item{
		line-height: 80rpx;
	}
	page {
		background-color: #FFFFFF;
	}
	
	.txt-title{
		font-size: 32rpx;
		line-height: 34rpx;
		font-weight: 700;
		margin: 20rpx;
	}
	.cu-form-group {
		justify-content: flex-start;
		width: 100%; 
		display: flex;
		margin-top: 30rpx;
	}
	
	.cu-form-group .title {
		padding-left: 30upx;
		padding-right: 0upx;
		word-break: break-all;
	}
	
	.cu-form-group+.cu-form-group {
		border-top: none;
	}
	
	.cu-bar-title {
		min-height: 50upx;
	}
	.red-border-a{
		border: 1px solid red !important;
	}
	.cu-list.menu>.cu-item-error {
		justify-content: flex-start;
	}

	.bg-red{
		border: 1px solid red;
	}
	
	.uni-padding-wrap {
		width: 690upx;
		padding: 0 30upx;
		box-sizing: content-box;
	}
	
	.uni-common-mt {
		margin-top: 30upx;
	}
	
	.uni-flex {
		display: flex;
		flex-direction: row;
	}
	
	.uni-row {
		flex-direction: row;
	}
	
	.text {
		margin: 15upx 10upx;
		padding: 0 20upx;
		/* background-color: #ebebeb; */
		height: 70upx;
		line-height: 70upx;
		text-align: center;
		color: #777;
		font-size: 26upx;
	}
	
	.showMask {  
	  position: fixed;  
	  top:0;  
	  left:0;  
	  z-index:999;  
	  width:100%;  
	  height:100vh;  
	  background:rgba(0,0,0,0.4);
	}  
	.cu-dialog{
		position: relative;
		display: inline-block;
		vertical-align: middle;
		margin-left: auto;
		margin-right: auto;
		width: 100%;
		max-width: 100%;
		background-color: #f8f8f8;
		border-radius: 5px;
		overflow: hidden;
	}
	.padding{
		padding: 30upx;
		box-sizing: content-box;
	}
	.cu-btn{
		    position: relative;
		    border: 0px;
		    display: -webkit-inline-box;
		    display: -webkit-inline-flex;
		    display: inline-flex;
		    -webkit-box-align: center;
		    -webkit-align-items: center;
		    align-items: center;
		    -webkit-box-pack: center;
		    -webkit-justify-content: center;
		    justify-content: center;
		    box-sizing: border-box;
		    padding: 0 15px;
		    font-size: 14px;
		    height: 32px;
				border-radius: 32px;
		    line-height: 1;
		    text-align: center;
		    text-decoration: none;
		    overflow: visible;
		    margin-left: initial;
		    -webkit-transform: translate(0px, 0px);
		    transform: translate(0px, 0px);
		    margin-right: initial;
	}
</style>
